package com.binguo.wxapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.binguo.common.exception.ErrorCode;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.paymodel.ThreadManager;
import com.binguo.common.util.FileDownloader;
import com.binguo.common.util.LoggerUtil;
import com.binguo.model.model.*;
import com.binguo.model.repository.CustomerRepository;
import com.binguo.model.wxapi.form.*;
import com.binguo.model.wxapi.result.ShopAPIResult;
import com.binguo.model.wxapi.vo.ISqlVO;
import com.binguo.model.wxapi.vo.ShopSideBoardVO;
import com.binguo.service.CustomerService;
import com.binguo.service.ISqlService;
import com.binguo.service.OrderService;
import com.binguo.service.ShopService;
import com.binguo.wxapi.form.DetailForm;
import com.binguo.wxapi.form.aiyouwei.SaveOrderForm;
import com.binguo.wxapi.form.api.ApiDeviceForm;
import com.binguo.wxapi.form.api.ApiPayForm;
import com.binguo.wxapi.form.openApiForm.ApiConfigForm;
import com.binguo.wxapi.form.openApiForm.ApiCustomerGroupCreateForm;
import com.binguo.wxapi.form.openApiForm.ApiCustomerGroupListForm;
import com.binguo.wxapi.result.Result;
import com.binguo.wxapi.result.ResultGenerator;
import com.binguo.wxapi.service.AiyouweiService;
import com.binguo.wxapi.service.ApiService;
import com.binguo.wxapi.service.ManKeBaoOrderForm;
import com.binguo.wxapi.service.RedisLockService;
import com.binguo.wxapi.util.EncryptUtils;
import com.binguo.wxapi.vo.ProductImgVO;
import com.binguo.wxapi.vo.external.CustomerVO;
import com.binguo.wxapi.vo.external.OrderResultVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Decoder;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@Api(tags = "对外接口")
@RestController
@RequestMapping
public class ApiController {
    private static Logger logger = LoggerFactory.getLogger(ApiController.class);

    @Autowired
    private CustomerRepository customerRepository;

    @Resource
    ApiService apiService;
    @Autowired
    OrderService orderService;

    @Resource
    RedisLockService redisLockService;

    BASE64Decoder decoder = new BASE64Decoder();
    @Autowired
    private AiyouweiService aiyouweiService;

    @Autowired
    ShopService shopService;

    @Resource
    ISqlService iSqlService;

    @Resource
    CustomerService customerService;

    private static String ipAddress = System.getenv("ipAddress");
    public String wxapiFilepath = "/usr/local/nginx/html";



    /**
     * 注册
     * @param registerForm
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/registerOrAddFace", produces = APPLICATION_JSON_VALUE)
    public Result registerOrAddFace(@RequestBody ApiRegisterForm registerForm) {
        if (StringUtils.isEmpty(registerForm.getPhone())
                || StringUtils.isEmpty(registerForm.getSign())
                || StringUtils.isEmpty(registerForm.getAppId())
                || StringUtils.isEmpty(registerForm.getUsername())
                ) {
            throw new ServiceException("参数错误");
        }

        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId",registerForm.getAppId());
        if(!StringUtils.isEmpty(registerForm.getCardNo())){
            param.put("cardNo",registerForm.getCardNo());
        }
        if (StringUtils.hasText(registerForm.getFaceUrl())) {
            param.put("faceUrl",registerForm.getFaceUrl());
        }
        if (registerForm.getGroupId() != null){
            param.put("groupId",registerForm.getGroupId().toString());
        }
        param.put("phone",registerForm.getPhone());
        param.put("username",registerForm.getUsername());

        String key = apiService.getKeyByAppID(registerForm.getAppId());

        String sign = generateSign(param, key);

        logger.info(sign);

        if (!key.equals(registerForm.getSign())) {
            if (!registerForm.getSign().equals(sign)) {
                throw new ServiceException("签名失败");
            }
        }

        if (StringUtils.hasText(registerForm.getFaceContentBase64())) {

            try {
                byte[] bytes1 = decoder.decodeBuffer(registerForm.getFaceContentBase64());
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
                BufferedImage bi1 = ImageIO.read(bais);

                String uuid = UUID.randomUUID().toString();
//                File f1 = new File("/usr/local/nginx/html/openapi/" + uuid + ".png");
//                ImageIO.write(bi1, "png", f1);

                String filepath = "/usr/local/nginx/html/openapi/" + uuid + ".png";
                File f1 = new File(filepath);
                ImageIO.write(bi1, "png", f1);

                String fileUrl = filepath.replace(wxapiFilepath, "http://" + ipAddress);
//                String fileUrl = "https://binguoai.com/openapi/" + uuid + ".png";
                logger.info("上传成功:newFileName==" + fileUrl);
                registerForm.setFaceUrl(fileUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else if (StringUtils.hasText(registerForm.getFaceUrl())) {
            String filepath = "/usr/local/nginx/html/openapi/source";
            File file = new File(filepath);

            if (!file.exists()) {
                file.mkdir();
            }

            String uuid = UUID.randomUUID().toString();
            String filename = filepath + "/" + uuid + ".png";

            FileDownloader.downloadNet(registerForm.getFaceUrl(), filename);

            String fileUrl = filename.replace(wxapiFilepath, "http://" + ipAddress);
//          String fileUrl = "https://binguoai.com/openapi/source/" + uuid + ".png";

            registerForm.setFaceUrl(fileUrl);
        }

        //ApiCustomerBriefVO apiCustomerBriefVO = new ApiCustomerBriefVO();
        //apiCustomerBriefVO.setUserId(customerId);

        return ResultGenerator.genSuccessResult(apiService.register(registerForm));
    }

    /**
     * 注销
     * @param getCustomerInfoForm
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/closeCustomer", produces = APPLICATION_JSON_VALUE)
    public Result close(@RequestBody ApiGetCustomerInfoForm getCustomerInfoForm) {
        if (StringUtils.isEmpty(getCustomerInfoForm.getPhone())
                || StringUtils.isEmpty(getCustomerInfoForm.getSign())
                || StringUtils.isEmpty(getCustomerInfoForm.getAppId())
                ) {
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",getCustomerInfoForm.getAppId());
        param.put("phone",getCustomerInfoForm.getPhone());

        String key = apiService.getKeyByAppID(getCustomerInfoForm.getAppId());

        String sign = generateSign(param, key);

        if (!key.equals(getCustomerInfoForm.getSign())) {
            if (!getCustomerInfoForm.getSign().equals(sign)) {
                throw new ServiceException("签名失败");
            }
        }

        apiService.close(getCustomerInfoForm);

        return ResultGenerator.genSuccessResult();
    }

    /**
     * 获取设备列表
     * @param form
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/getDeviceList", produces = APPLICATION_JSON_VALUE)
    public Result getDeviceList(@RequestBody ApiDeviceForm form) {
        if (StringUtils.isEmpty(form.getSign())
                || StringUtils.isEmpty(form.getAppId())
                || (form.getPage() != null && form.getPage()<1)
                ) {
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",form.getAppId());

        String key = apiService.getKeyByAppID(form.getAppId());
        String sign = generateSign(param, key);
        logger.info(sign);

        if (!key.equals(form.getSign())) {
            if (!form.getSign().equals(sign)) {
                throw new ServiceException("签名失败");
            }
        }

        return ResultGenerator.genSuccessResult(apiService.getDeviceList(form));
    }

    /**
     *
     * @param getCustomerInfoForm
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/getUserInfo", produces = APPLICATION_JSON_VALUE)
    public Result getCustomerInfo(@RequestBody ApiGetCustomerInfoForm getCustomerInfoForm){
        if (StringUtils.isEmpty(getCustomerInfoForm.getPhone())
                || StringUtils.isEmpty(getCustomerInfoForm.getAppId())
                || StringUtils.isEmpty(getCustomerInfoForm.getSign())
                ) {
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",getCustomerInfoForm.getAppId());
        param.put("phone",getCustomerInfoForm.getPhone());
        String key = apiService.getKeyByAppID(getCustomerInfoForm.getAppId());
        String sign = generateSign(param, key);

        if(!getCustomerInfoForm.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }


        Condition condition = new Condition(Customer.class);
        condition.or().andEqualTo("phone", getCustomerInfoForm.getPhone());

        List<Customer> customerList = customerRepository.findByCondition(condition);

        if (customerList != null && customerList.size() > 0) {
            Customer customer = customerList.get(0);


            CustomerVO customerVO = new CustomerVO();
            customerVO.setCustomerId(customer.getId());
            customerVO.setCustomerName(customer.getName());


            PayCard payCard = apiService.getPayCard(customer.getId(), getCustomerInfoForm.getAppId());

            if (payCard != null) {
                customerVO.setBalance(payCard.getAccountbalance());
                customerVO.setQrCode(payCard.getPayCode());
            }else {
                customerVO.setBalance(0l);

            }

            return ResultGenerator.genSuccessResult(customerVO);
        }


        throw new ServiceException("用户不存在");
    }


    /**
     *
     * @param getCustomerInfoForm
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/getUserList", produces = APPLICATION_JSON_VALUE)
    public Result getUserList(@RequestBody ApiGetCustomerInfoListForm getCustomerInfoForm){
        if (StringUtils.isEmpty(getCustomerInfoForm.getAppId())
                || StringUtils.isEmpty(getCustomerInfoForm.getSign())
                ) {
            throw new ServiceException("参数错误");
        }
        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId",getCustomerInfoForm.getAppId());
        if(null != getCustomerInfoForm.getGroupName()){
            param.put("groupName", getCustomerInfoForm.getGroupName());
        }
        if (null != getCustomerInfoForm.getCardNo()) {
            param.put("cardNo", getCustomerInfoForm.getCardNo());
        }
        if (null != getCustomerInfoForm.getPhone()) {
            param.put("phone", getCustomerInfoForm.getPhone());
        }
        if (null != getCustomerInfoForm.getUserName()) {
            param.put("userName", getCustomerInfoForm.getUserName());
        }
        if (null != getCustomerInfoForm.getStartTime()) {
            param.put("startTime", getCustomerInfoForm.getStartTime());
        }
        if (null != getCustomerInfoForm.getPage()) {
            param.put("page", getCustomerInfoForm.getPage().toString());
        } else {
            getCustomerInfoForm.setPage(1);
        }
        String key = apiService.getKeyByAppID(getCustomerInfoForm.getAppId());
        String sign = generateSign(param, key);
        logger.info(sign);
        if (!key.equals(getCustomerInfoForm.getSign())) {
            if (!getCustomerInfoForm.getSign().equals(sign)) {
                throw new ServiceException("签名失败");
            }
        }

        return ResultGenerator.genSuccessResult(apiService.getUserLists(getCustomerInfoForm));
    }


    /**
     * 充值
     * @param rechargeForm
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/recharge", produces = APPLICATION_JSON_VALUE)
    public Result yhcz(@RequestBody ApiRechargeForm rechargeForm){
        if (StringUtils.isEmpty(rechargeForm.getPhone())
                || StringUtils.isEmpty(rechargeForm.getAppId())
                || StringUtils.isEmpty(rechargeForm.getSign())
                || StringUtils.isEmpty(rechargeForm.getAmount())
                || StringUtils.isEmpty(rechargeForm.getOrderNo())
                || StringUtils.isEmpty(rechargeForm.getOrderTime())
                ) {
            throw new ServiceException("参数错误");
        }

        try {
            LoggerUtil.console.info("recharge:{}", com.binguo.common.util.JsonUtil.toJson(rechargeForm));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        Map<String, String> param = new TreeMap<>();
        param.put("appId",rechargeForm.getAppId());
        param.put("amount",rechargeForm.getAmount());
        param.put("orderNo",rechargeForm.getOrderNo());
        param.put("orderTime",rechargeForm.getOrderTime());
        param.put("phone",rechargeForm.getPhone());
        param.put("username",rechargeForm.getUsername());
        String key = apiService.getKeyByAppID(rechargeForm.getAppId());
        String sign = generateSign(param, key);

        if(!rechargeForm.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }

        String lockKey = rechargeForm.getOrderNo();


//        String uuid = UUID.randomUUID().toString();
//        boolean lock = redisLockService.setLock(lockKey, 10000, uuid);
//        if (lock) {
            apiService.recharge(rechargeForm);
            return ResultGenerator.genSuccessResult();
//        } else {
//            throw new ServiceException("订单正在处理中");
//        }

    }


    /**
     * 消费
     * @param rechargeForm
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/pay", produces = APPLICATION_JSON_VALUE)
    public Result pay(@RequestBody ApiPayForm rechargeForm){
        if (StringUtils.isEmpty(rechargeForm.getBizOrderNo())
                || StringUtils.isEmpty(rechargeForm.getAppId())
                || StringUtils.isEmpty(rechargeForm.getSign())
                || StringUtils.isEmpty(rechargeForm.getAmount())
                || StringUtils.isEmpty(rechargeForm.getCardNo())
                || StringUtils.isEmpty(rechargeForm.getOrderTime())
                ) {
            throw new ServiceException("参数错误");
        }

        try {
            LoggerUtil.console.info("pay:{}", com.binguo.common.util.JsonUtil.toJson(rechargeForm));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        Map<String, String> param = new TreeMap<>();
        param.put("appId",rechargeForm.getAppId());
        param.put("amount",rechargeForm.getAmount().toString());
        param.put("bizOrderNo",rechargeForm.getBizOrderNo());
        param.put("cardNo",rechargeForm.getCardNo());
        param.put("orderTime",rechargeForm.getOrderTime().toString());
        String key = apiService.getKeyByAppID(rechargeForm.getAppId());
        String sign = generateSign(param, key);

        if(!rechargeForm.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }

        String uuid = UUID.randomUUID().toString();
//        boolean lock = redisLockService.setLock(rechargeForm.getBizOrderNo(), 10000, uuid);
//        if (lock) {
            apiService.orderPay(rechargeForm);
            return ResultGenerator.genSuccessResult();
//        } else {
//            throw new ServiceException("订单正在处理中");
//        }

    }

    /**
     * 查询消费订单列表
     * @param orderListForm
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/orderList", produces = APPLICATION_JSON_VALUE)
    public Result orderList(@RequestBody ApiOrderListForm orderListForm) {
        if (StringUtils.isEmpty(orderListForm.getAppId())
                || StringUtils.isEmpty(orderListForm.getSign())
                || (orderListForm.getPage() != null && orderListForm.getPage()<1)
        ) {
            throw new ServiceException("参数错误");
        }

        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId", orderListForm.getAppId());
        if (null != orderListForm.getPhone()) {
            param.put("phone", orderListForm.getPhone());
        }
        if (null != orderListForm.getUserName()) {
            param.put("userName", orderListForm.getUserName());
        }
        if (null != orderListForm.getStartTime()) {
            param.put("startTime", orderListForm.getStartTime());
        }
        if (null != orderListForm.getEndTime()) {
            param.put("endTime", orderListForm.getEndTime());
        }
        if (null != orderListForm.getPage()){
            param.put("page",orderListForm.getPage().toString());
        }
        if (null != orderListForm.getOrderType()){
            param.put("orderType",orderListForm.getOrderType().toString());
        }
        if (null != orderListForm.getSource()){
            param.put("source",orderListForm.getSource().toString());
        }
        if (null != orderListForm.getGroupId()){
            param.put("groupId",orderListForm.getGroupId().toString());
        }
        String key = apiService.getKeyByAppID(orderListForm.getAppId());

        String sign = generateSign(param, key);

        logger.info(sign);
        if (!key.equals(orderListForm.getSign())) {
            if (!orderListForm.getSign().equals(sign)) {
                throw new ServiceException("签名失败");
            }
        }
        OrderResultVO orderResultVO = apiService.orderLists(orderListForm);
        return ResultGenerator.genSuccessResult(orderResultVO);
    }


    /**
     *
     * @param getCustomerInfoForm
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/getProductList", produces = APPLICATION_JSON_VALUE)
    public Result getProductList(@RequestBody ApiGetCustomerInfoListForm getCustomerInfoForm){
        if (StringUtils.isEmpty(getCustomerInfoForm.getAppId())
                || StringUtils.isEmpty(getCustomerInfoForm.getSign())
                ) {
            throw new ServiceException("参数错误");
        }
        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",getCustomerInfoForm.getAppId());
        if (getCustomerInfoForm.getBranchId() != null) {
            param.put("branchId", getCustomerInfoForm.getBranchId().toString());
        }
        String key = apiService.getKeyByAppID(getCustomerInfoForm.getAppId());
        String sign = generateSign(param, key);
        logger.info(sign);
        if (!key.equals(getCustomerInfoForm.getSign())) {
            if(!getCustomerInfoForm.getSign().equals(sign)){
                throw new ServiceException("签名失败");
            }
        }
        logger.info("调用getProductList方法,入参:branchId:"+getCustomerInfoForm.getBranchId());
        return ResultGenerator.genSuccessResult(apiService.getProductList(getCustomerInfoForm.getAppId(),getCustomerInfoForm.getPage(),getCustomerInfoForm.getBranchId()));
    }



    /**
     *
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/addProduct", produces = APPLICATION_JSON_VALUE)
    public Result addProduct(@RequestBody ApiProductForm form){
        if (StringUtils.isEmpty(form.getAppId())
                || StringUtils.isEmpty(form.getPrice())
                || StringUtils.isEmpty(form.getProductCode())
                || StringUtils.isEmpty(form.getProductName())
                || StringUtils.isEmpty(form.getSign())
                ) {
            throw new ServiceException("参数错误");
        }

        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId",form.getAppId());
        param.put("categoryName",form.getCategoryName());
        param.put("price",form.getPrice().toString());
        param.put("productCode",form.getProductCode());
        if(form.getProductImage() != null){
            param.put("productImage",form.getProductImage());
        }
        param.put("productName",form.getProductName());
        param.put("branchId",form.getBranchId().toString());

        String key = apiService.getKeyByAppID(form.getAppId());

        String sign = generateSign(param, key);

        if(!form.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }

        Integer productId = apiService.addProduct(form);
        Map map = new HashMap();
        map.put("productId",productId);

        return ResultGenerator.genSuccessResult();
    }

    /**
     *
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/delProduct", produces = APPLICATION_JSON_VALUE)
    public Result delProduct(@RequestBody ApiDelProductForm form){
        if (StringUtils.isEmpty(form.getAppId())
                || StringUtils.isEmpty(form.getProductCode())
                || StringUtils.isEmpty(form.getSign())
                ) {
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",form.getAppId());
        param.put("productCode",form.getProductCode());

        String key = apiService.getKeyByAppID(form.getAppId());

        String sign = generateSign(param, key);

        if(!form.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }
        apiService.delProduct(form);

        return ResultGenerator.genSuccessResult();
    }



    public static String generateSign(Map<String, String> param, String appKey) {
        StringBuilder sb = new StringBuilder();

        for (Map.Entry<String,String> en : param.entrySet()) {
            sb.append(en.getKey()).append("=").append(en.getValue()).append("&");
        }
        sb.append("key=").append(appKey);

        logger.info("代签名字符串"+ sb.toString());

        String sign = EncryptUtils.md5(sb.toString()).toUpperCase();
        return sign;
    }

    @PostMapping("/wxapi/getSign")
    public Result getSign(@RequestBody SaveOrderForm form){
        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId",form.getAppId());
        param.put("orderUrl",form.getOrderUrl());
        String key = apiService.getKeyByAppID(form.getAppId());
        String sign = ApiController.generateSign(param, key);
        logger.info("生成签名:"+sign);
        return ResultGenerator.genSuccessResult(sign);
    }


    /**
     * 创建分店
     * @param branchEditForm
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/createBranch", produces = APPLICATION_JSON_VALUE)
    public Result createBranch(@RequestBody ApiBranchEditForm branchEditForm) {
        logger.info("进入创建分店方法！");
        if (StringUtils.isEmpty(branchEditForm.getAppId())
                || StringUtils.isEmpty(branchEditForm.getSign())
                || null == branchEditForm.getBranchId()
                || null == branchEditForm.getBranchName()
        ) {
            throw new ServiceException("参数错误");
        }
        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId", branchEditForm.getAppId());
        param.put("branchId",branchEditForm.getBranchId().toString());
        param.put("branchName",branchEditForm.getBranchName());
        String key = apiService.getKeyByAppID(branchEditForm.getAppId());

        String sign = generateSign(param, key);
        logger.info("效验签名！ 传入签名:"+branchEditForm.getSign()+"生成签名:"+sign);
        if (!key.equals(branchEditForm.getSign())) {
            if(!branchEditForm.getSign().equals(sign)){
                throw new ServiceException("签名失败");
            }
        }
        int num = 0;
        if(branchEditForm.getBranchId().equals(0)){
            logger.info("创建分店");
            Branch branch = apiService.addBranch(branchEditForm);
            if(null != branch){
                Map map = new HashMap();
                map.put("branchId",branch.getBranchId());
                map.put("shopId",branch.getShopId());
                map.put("branchName",branch.getBranchName());
                return  ResultGenerator.genSuccessResult(map);
            }else{
                return ResultGenerator.genFailResult("创建分店失败");
            }
        }else{
            logger.info("更新分店");
            num = apiService.updateBranch(branchEditForm);
            if (num > 0){
                return ResultGenerator.genSuccessResult(null);
            }else{
                return ResultGenerator.genFailResult("修改分店失败");
            }
        }


    }

    /**
     * 删除人脸
     * @param apiFaceDeleteForm
     * @return
     */
    @PostMapping("/api/wxapp/openapi/deletePersonFace")
    public Result deletePersonFace(@RequestBody ApiFaceDeleteForm apiFaceDeleteForm){
        logger.info("进入删除人脸方法,入参:"+apiFaceDeleteForm.toString());
        if (StringUtils.isEmpty(apiFaceDeleteForm.getAppId())
                || StringUtils.isEmpty(apiFaceDeleteForm.getSign())
                || StringUtils.isEmpty(apiFaceDeleteForm.getCustomerId())
        ) {
            throw new ServiceException("参数错误");
        }
        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId", apiFaceDeleteForm.getAppId());
        param.put("customerId",apiFaceDeleteForm.getCustomerId());
        if (apiFaceDeleteForm.getFaceId() != null) {
            param.put("faceId", apiFaceDeleteForm.getFaceId());
        }
        String key = apiService.getKeyByAppID(apiFaceDeleteForm.getAppId());

        String sign = generateSign(param, key);
        logger.info("效验签名！  传入签名:"+apiFaceDeleteForm.getSign()+"生成签名:"+sign);
        if (!key.equals(apiFaceDeleteForm.getSign())) {
            if(!apiFaceDeleteForm.getSign().equals(sign)){
                throw new ServiceException("签名失败");
            }
        }
        logger.info("调用删除人脸方法,入参:"+apiFaceDeleteForm);
        boolean flag = apiService.deleteFace(apiFaceDeleteForm);
        logger.info("调用删除人脸方法，返回:"+flag);
        if (flag){
            return ResultGenerator.genSuccessResult();
        }else{
            return ResultGenerator.genFailResult("删除失败");
        }
    }

    /**
     *  修改菜品
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/updateProduct", produces = APPLICATION_JSON_VALUE)
    public Result updateProduct(@RequestBody ApiProductForm form){
        logger.info("进入更新菜品方法,入参:"+form.toString());
        if (StringUtils.isEmpty(form.getAppId())
                || StringUtils.isEmpty(form.getProductCode())
                || StringUtils.isEmpty(form.getSign())
        ) {
            throw new ServiceException("参数错误");
        }

        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId",form.getAppId());
        param.put("productCode",form.getProductCode());
        if (!StringUtils.isEmpty(form.getProductName())){
            param.put("productName",form.getProductName());
        }
        if (!StringUtils.isEmpty(form.getCategoryName())){
            param.put("categoryName",form.getCategoryName());
        }
        if (form.getPrice() != null){
            param.put("price",form.getPrice().toString());
        }
        if (form.getBranchId() != null){
            param.put("branchId",form.getBranchId().toString());
        }
        String key = apiService.getKeyByAppID(form.getAppId());

        String sign = generateSign(param, key);
        logger.info("效验签名！  传入签名:"+form.getSign()+"生成签名:"+sign);
        if(!form.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }
        logger.info("执行更新product表操作");
        apiService.updateProduct(form);
        return ResultGenerator.genSuccessResult();
    }

    /**
     *  修改用户
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/updateCustomer", produces = APPLICATION_JSON_VALUE)
    public Result updateCustomer(@RequestBody ApiGetCustomerInfoListForm form){
        logger.info("进入更新用户方法,入参:"+form.toString());
        if (StringUtils.isEmpty(form.getAppId())
                || StringUtils.isEmpty(form.getPhone())
                || StringUtils.isEmpty(form.getUserName())
                || StringUtils.isEmpty(form.getUserId())
                || StringUtils.isEmpty(form.getSign())
        ) {
            throw new ServiceException("参数错误");
        }

        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId",form.getAppId());
        param.put("userId",form.getUserId().toString());
        param.put("userName",form.getUserName());
        param.put("phone",form.getPhone());
        String key = apiService.getKeyByAppID(form.getAppId());

        String sign = generateSign(param, key);
        logger.info("效验签名！  传入签名:"+form.getSign()+"生成签名:"+sign);
        if(!form.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }
        logger.info("执行更新Customer表操作");
        int flag = apiService.updateUser(form);
        if(flag <= 0){
            return ResultGenerator.genFailResult("更新失败");
        }
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping(value = "/api/wxapp/openapi/openSideBoard" , produces = APPLICATION_JSON_VALUE)
    public Result openSideBoard(@RequestBody ApiOpencellForm form){
        logger.info("进入开柜方法");
        if (StringUtils.isEmpty(form.getAppId())
                || StringUtils.isEmpty(form.getSideBoardId())
                || StringUtils.isEmpty(form.getInfo().getCellNo())
                || StringUtils.isEmpty(form.getSign())
        ) {
            throw new ServiceException("参数错误");
        }
        form.getInfo().setOpen(true);
        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId",form.getAppId());
        param.put("info",form.getInfo().toString());
        param.put("sideBoardId",form.getSideBoardId().toString());
        String key = apiService.getKeyByAppID(form.getAppId());

        String sign = generateSign(param, key);
        logger.info("效验签名！  传入签名:"+form.getSign()+"生成签名:"+sign);
        if(!form.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }
        logger.info("调用开柜接口:"+form.getInfo());
        boolean flag = apiService.openSideBoardCell(form);
        if (flag == true){
            return ResultGenerator.genSuccessResult("操作成功");
        }else{
            return ResultGenerator.genFailResult("操作失败");
        }
    }

    @PostMapping(value = "/api/wxapp/openapi/getSideBoardList", produces = APPLICATION_JSON_VALUE)
    public Result selectSideBoard(@RequestBody ApiGetSideBoardListForm form){
        logger.info("进入查询方法");
        if (StringUtils.isEmpty(form.getAppId())
                || StringUtils.isEmpty(form.getSign())
        ) {
            throw new ServiceException("参数错误");
        }
        logger.info("进入获取商户取餐柜列表方法");
        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId",form.getAppId());
        String key = apiService.getKeyByAppID(form.getAppId());

        String sign = generateSign(param, key);
        logger.info("效验签名！  传入签名:"+form.getSign()+"生成签名:"+sign);
        if(!form.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }
        logger.info("调用获取商户取餐柜列表接口:"+form.getAppId());
        List<ShopSideBoardVO> shopSideBoardVOS = apiService.getSideBoardList(form);
        if (shopSideBoardVOS.size()>0 || shopSideBoardVOS != null){
            List<Map> list = new ArrayList<>();
            for(ShopSideBoardVO shopSideBoardVO : shopSideBoardVOS){
                Map map = new HashMap();
                map.put("branchId",shopSideBoardVO.getBranchId());
                map.put("deviceId",shopSideBoardVO.getCashierDeskId());
                map.put("tag",shopSideBoardVO.getBranchSideBoardId());
                list.add(map);
            }
            return ResultGenerator.genSuccessResult(list);
        }else{
            return ResultGenerator.genFailResult("商户暂未绑定取餐柜。");
        }
    }

    @PostMapping(value = "/api/wxapp/openapi/createShop" , produces = APPLICATION_JSON_VALUE)
    public Result createShop(@RequestBody ApiCreateShopForm form){
        if (StringUtils.isEmpty(form.getPhone())
                || StringUtils.isEmpty(form.getShopName())
                || StringUtils.isEmpty(form.getSign())
                || StringUtils.isEmpty(form.getChannelNo())
                || null == form.getIsIdentify()
                || null == form.getIsRecharge()
                || null == form.getIsReserve()
                || null == form.getIsYpCard()
        ) {
            throw new ServiceException("参数错误");
        }


        ShopChannel shopChannel = shopService.checkShopChannelNo(form.getChannelNo());

        String key = shopChannel.getChannelSecret();

        TreeMap<String, String> param = new TreeMap<>();
        param.put("phone",form.getPhone());
        param.put("shopName",form.getShopName());
        param.put("isIdentify",form.getIsIdentify().toString());
        param.put("isReserve",form.getIsReserve().toString());
        param.put("isRecharge",form.getIsRecharge().toString());
        param.put("isYpCard",form.getIsYpCard().toString());
        param.put("channelNo",form.getChannelNo());


        String sign = generateSign(param, key);
        logger.info("效验签名！  传入签名:"+form.getSign()+"生成签名:"+sign);
        if(!form.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }

        Shop shop = shopService.getShopByPhone(form.getPhone());
        if(null != shop){
            throw new ServiceException("商户的手机号已重复");
        }

        Integer type = shopChannel.getType();

        if (type.equals(1)) {
            shopService.createShopFromOpenAPI(form,shopChannel);
            ShopAPIResult result = shopService.getAppMsg(form.getPhone());
            return ResultGenerator.genSuccessResult(result);
        } else {
            shopService.saveShopTemp(form);
            throw new ServiceException(ErrorCode.SHOP_WAIT_EXISTS);
        }
    }

    @PostMapping(value = "/api/wxapp/openapi/createShopByTemp" , produces = APPLICATION_JSON_VALUE)
    public Result createShopByTemp(@RequestBody ApiCreateShopForm form) {
        Shop shop = shopService.getShopByPhone(form.getPhone());
        if(null != shop){
            throw new ServiceException("商户的手机号已重复");
        }
        ShopChannel shopChannel = shopService.checkShopChannelNo(form.getChannelNo());
        shopService.createShopFromOpenAPI(form,shopChannel);
        String phone = form.getPhone();
        String postUrl = shopService.getPostUrl(form.getChannelNo());
        ThreadManager.executorService.submit(new Runnable() {
            @Override
            public void run() {
                String key = shopChannel.getChannelSecret();
                TreeMap<String, String> param = new TreeMap<>();

                ShopAPIResult result = shopService.getAppMsg(form.getPhone());
                param.put("appId",result.getAppId());
                param.put("appSecret",result.getAppSecret());
                param.put("phone",phone);
                String sign = generateSign(param,key);


                JSONObject postParam = new JSONObject();
                postParam.put("appId",result.getAppId());
                postParam.put("appSecret",result.getAppSecret());
                postParam.put("phone",phone);
                postParam.put("sign",sign);

                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                logger.info("发送参数:  " + postParam);
               try {
                   HttpEntity<String> entity = new HttpEntity<String>(postParam.toJSONString(), headers);
                   ResponseEntity<String> resp = restTemplate.postForEntity(postUrl, entity, String.class);
                   logger.info(resp.getBody());
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        logger.info(JSONObject.toJSONString(form));
        return ResultGenerator.genSuccessResult();
    }

    @CrossOrigin("*")
    @PostMapping(value = "/api/wxapp/openapi/iSqlquery" , produces = APPLICATION_JSON_VALUE)
    public Result createShop(@RequestBody String jsonParam){
        JSONObject webJson = JSON.parseObject(jsonParam);
        ISqlVO iSqlVO = new ISqlVO();
        iSqlVO.setSql_id(webJson.getString("sql_id"));
        iSqlVO.setParams(webJson.getJSONObject("params"));
        iSqlVO.setPage_num(webJson.getInteger("page_num"));
        iSqlVO.setPage_size(webJson.getInteger("page_size"));
        return ResultGenerator.genSuccessResult(iSqlService.runSql(iSqlVO));
    }


    /**
     * 新建收银员或者修改收银员登陆密码
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/addOrUpdateEmployee", produces = APPLICATION_JSON_VALUE)
    public Result addOrUpdateEmployee(@RequestBody ApiEmployeeForm form){
        logger.info("进入收银员方法,入参:"+form.toString());
        if (StringUtils.isEmpty(form.getAppId())
                || StringUtils.isEmpty(form.getSign())
                || StringUtils.isEmpty(form.getAccount())
                || StringUtils.isEmpty(form.getPassword())
                || StringUtils.isEmpty(form.getAction())
        ) {
            throw new ServiceException("参数错误");
        }
        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId",form.getAppId());
        param.put("account",form.getAccount());
        param.put("password",form.getPassword());
        param.put("action",form.getAction().toString());
        String key = apiService.getKeyByAppID(form.getAppId());
        String sign = generateSign(param, key);
        logger.info("效验签名！  传入签名:"+form.getSign()+"生成签名:"+sign);
        if(!form.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }
        boolean flag = false ;
        if(form.getAction() == 1){
            flag = apiService.addEmployee(form);
        }else if(form.getAction() == 2){
            flag = apiService.updateEmployee(form);
        }else{
            ResultGenerator.genFailResult("action错误");
        }
        return flag ? ResultGenerator.genSuccessResult() : ResultGenerator.genFailResult("注册失败！");
    }

    @PostMapping(value = "/api/wxapp/openapi/settlementCreat", produces = APPLICATION_JSON_VALUE)
    public Result settlementCreat()throws  Exception{
        logger.info("进入订单推送");
        DetailForm [] detailForms = new DetailForm[1];
        DetailForm detailForm = new DetailForm();
        detailForm.setItemCode("10792");
        detailForm.setCount("1");
        detailForms[0] = detailForm;
        ManKeBaoOrderForm orderForm = new ManKeBaoOrderForm("0477376994", "EDA42546A6", "265", "LC158477856447841", "false", null, String.valueOf(System.currentTimeMillis()), "ZHANGSAN", "13688885555", "13936458876", detailForms);
        Boolean flag = apiService.settlementCreat(orderForm, "YunPeng20000000239");
        if(flag){
            return ResultGenerator.genSuccessResult(flag);
        }else{
            return ResultGenerator.genFailResult("操作失败!");
        }

    }


    @PostMapping(value = "/api/wxapp/openapi/getCustomerGroupList", produces = APPLICATION_JSON_VALUE)
    public Result getCustomerGroupList(@RequestBody ApiCustomerGroupListForm form){
        if (StringUtils.isEmpty(form.getAppId())
                || (form.getPage() != null && form.getPage() < 1)
                || StringUtils.isEmpty(form.getSign())
        ) {
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",form.getAppId());
        if (form.getPage() != null) {
            param.put("page", form.getPage().toString());
        }

        String key = apiService.getKeyByAppID(form.getAppId());

        String sign = generateSign(param, key);

        logger.info(sign);

        if(!form.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }

        return ResultGenerator.genSuccessResult(apiService.getCustomerGroupList(form));
    }


    @PostMapping(value = "/api/wxapp/openapi/createCustomerGroup", produces = APPLICATION_JSON_VALUE)
    public Result createCustomerGroup(@RequestBody ApiCustomerGroupCreateForm form){
        if (StringUtils.isEmpty(form.getAppId())
                || StringUtils.isEmpty(form.getName())
                || StringUtils.isEmpty(form.getSign())
        ) {
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",form.getAppId());
        param.put("name",form.getName());

        String key = apiService.getKeyByAppID(form.getAppId());

        String sign = generateSign(param, key);

        logger.info(sign);

        if(!form.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }

        Boolean result = customerService.checkGroupName(form.getName());
        if (result){
            throw new ServiceException("该店铺下此会员名称已经存在");
        }
        return ResultGenerator.genSuccessResult(apiService.saveCustomerGroup(form));
    }

    @PostMapping(value = "/api/wxapp/openapi/updateCustomerGroup", produces = APPLICATION_JSON_VALUE)
    public Result updateCustomerGroup(@RequestBody JSONObject postParam){

        String appId = postParam.getString("appId");

        String postSign = postParam.getString("sign");

        Integer id = postParam.getInteger("groupId");

        String groupName = postParam.getString("groupName");

        if (StringUtils.isEmpty(appId)
                || StringUtils.isEmpty(postSign)
                || id == null
                || StringUtils.isEmpty(groupName)
        ) {
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",appId);
        param.put("id",id.toString());
        param.put("groupName",groupName);

        String key = apiService.getKeyByAppID(appId);

        String sign = generateSign(param, key);

        logger.info(sign);

        if(!postSign.equals(sign)){
            throw new ServiceException("签名失败");
        }

        apiService.updateCustomerGroup(groupName,id,appId);

        return ResultGenerator.genSuccessResult();
    }


    @PostMapping(value = "/api/wxapp/openapi/getProducrCategoryList", produces = APPLICATION_JSON_VALUE)
    public Result getProducrCategoryList(@RequestBody JSONObject postParam){
        String appId = postParam.getString("appId");

        String postSign = postParam.getString("sign");

        Integer page = postParam.getInteger("page");

        if (StringUtils.isEmpty(appId)
                || StringUtils.isEmpty(postSign)
                || (page != null && page < 1)
        ) {
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",appId);
        if (page != null) {
            param.put("page", page.toString());
        }

        String key = apiService.getKeyByAppID(appId);

        String sign = generateSign(param, key);

        logger.info(sign);

        if(!postSign.equals(sign)){
            throw new ServiceException("签名失败");
        }

        return ResultGenerator.genSuccessResult(apiService.getProductCategoryList(appId,page));
    }

    @PostMapping(value = "/api/wxapp/openapi/createProducrCategory", produces = APPLICATION_JSON_VALUE)
    public Result createProducrCategory(@RequestBody JSONObject postParam){

        String appId = postParam.getString("appId");

        String name = postParam.getString("name");

        String postSign = postParam.getString("sign");

        if (StringUtils.isEmpty(appId)
                || StringUtils.isEmpty(postSign)
                || StringUtils.isEmpty(name)
        ) {
            throw new ServiceException("参数错误");
        }



        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",appId);
        param.put("name",name);


        String key = apiService.getKeyByAppID(appId);

        String sign = generateSign(param, key);

        logger.info(sign);

        if(!postSign.equals(sign)){
            throw new ServiceException("签名失败");
        }


        return ResultGenerator.genSuccessResult(apiService.saveProductCategory(appId,name));
    }

    @PostMapping(value = "/api/wxapp/openapi/createProductImg", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "添加菜品图片", notes = "通过CreateCardForm")
    public Result create(@RequestBody JSONObject postParam) {


        String appId = postParam.getString("appId");

        Integer productId = postParam.getInteger("productId");

        String productUrl = postParam.getString("productUrl");

        String productBase64 = postParam.getString("productBase64");

        String postSign = postParam.getString("sign");


        if (StringUtils.isEmpty(appId)
                || StringUtils.isEmpty(postSign)
                || productId == null) {
            throw new ServiceException("参数错误");
        }

        if (!(StringUtils.isEmpty(productUrl) || StringUtils.isEmpty(productBase64))){
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",appId);
        param.put("productId",productId.toString());
        if (!StringUtils.isEmpty(productUrl)){
            param.put("productUrl",productUrl);
        }

        String key = apiService.getKeyByAppID(appId);

        String sign = generateSign(param, key);

        logger.info(sign);

        if(!postSign.equals(sign)){
            throw new ServiceException("签名失败");
        }


        boolean result = apiService.addProductImg(appId,productId,productUrl,productBase64);
        if (result) {
            return ResultGenerator.genSuccessResult("添加成功");
        } else {
            return ResultGenerator.genFailResult("添加失败");
        }
    }


    @PostMapping(value = "/api/wxapp/openapi/productimg/del", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除菜品图片", notes = "通过DelProductImgForm")
    public Result delFace(@RequestBody JSONObject postParam) {

        String appId = postParam.getString("appId");

        Integer productId = postParam.getInteger("productId");

        Integer productImgId = postParam.getInteger("productImgId");

        String postSign = postParam.getString("sign");

        if (StringUtils.isEmpty(appId)
                || StringUtils.isEmpty(postSign)
                || productId == null
                || productImgId == null)
        {
            throw new ServiceException("参数错误");
        }


        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",appId);
        param.put("productId",productId.toString());
        param.put("productImgId",productImgId.toString());

        String key = apiService.getKeyByAppID(appId);

        String sign = generateSign(param, key);

        logger.info(sign);

        if(!postSign.equals(sign)){
            throw new ServiceException("签名失败");
        }

        apiService.deleteProductImg(appId,productId,productImgId);

        return ResultGenerator.genSuccessResult();
    }

    @PostMapping(value = "/api/wxapp/openapi/getProductImgList", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取菜品图片列表", notes = "")
    public Result productImgList(@RequestBody JSONObject postParam) {

        String appId = postParam.getString("appId");

        Integer productId = postParam.getInteger("productId");

        String postSign = postParam.getString("sign");


        if (StringUtils.isEmpty(appId)
                || StringUtils.isEmpty(postSign)
                || productId == null) {
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",appId);
        param.put("productId",productId.toString());

        String key = apiService.getKeyByAppID(appId);

        String sign = generateSign(param, key);

        logger.info(sign);

        if(!postSign.equals(sign)){
            throw new ServiceException("签名失败");
        }

        List<ProductImgVO> productImgVOList = apiService.getProductImgList(appId,productId);
        if (productImgVOList == null || productImgVOList.size() == 0){
            throw new ServiceException("不存在菜品图片");
        }

        JSONObject result = new JSONObject();
        result.put("productImgList",productImgVOList);

        return ResultGenerator.genSuccessResult(result);
    }

    @PostMapping(value = "/api/wxapp/openapi/customerPay", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "会员支付", notes = "")
    public Result customerPay(@RequestBody JSONObject postParam) {

        String appId = postParam.getString("appId");

        Integer customerId = postParam.getInteger("customerId");

        String cardId = postParam.getString("cardId");

        String cardNo = postParam.getString("cardNo");

        Long realFee = postParam.getLong("realFee");

        String postSign = postParam.getString("sign");


        if (StringUtils.isEmpty(appId)
                || StringUtils.isEmpty(postSign)) {
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",appId);
        param.put("realFee",realFee.toString());
        if (customerId != null) {
            param.put("customerId", customerId.toString());
        }
        if (StringUtils.isEmpty(cardId)){
            param.put("cardId",cardId);
        }
        if (StringUtils.isEmpty(cardNo)){
            param.put("cardNo",cardNo);
        }

        String key = apiService.getKeyByAppID(appId);

        String sign = generateSign(param, key);

        logger.info(sign);

        if(!postSign.equals(sign)){
            throw new ServiceException("签名失败");
        }

        apiService.customerPay(appId,customerId,cardNo,cardId,realFee);
        return ResultGenerator.genSuccessResult("");
    }


    @PostMapping(value = "/api/wxapp/openapi/getBranchList", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取分店列表", notes = "")
    public Result branchList(@RequestBody JSONObject postParam) {

        String appId = postParam.getString("appId");

        Integer page = postParam.getInteger("page");

        String postSign = postParam.getString("sign");


        if (StringUtils.isEmpty(appId)
                || StringUtils.isEmpty(postSign)) {
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",appId);
        if (page != null) {
            param.put("page", page.toString());
        }

        String key = apiService.getKeyByAppID(appId);

        String sign = generateSign(param, key);

        logger.info(sign);

        if(!postSign.equals(sign)){
            throw new ServiceException("签名失败");
        }
        return ResultGenerator.genSuccessResult(apiService.getBranchList(appId,page));
    }

    @PostMapping(value = "/api/wxapp/openapi/addFace", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "添加人脸", notes = "")
    public Result addFace(@RequestBody JSONObject postParam) {

        String appId = postParam.getString("appId");

        Integer customerId = postParam.getInteger("customerId");

        String faceUrl = postParam.getString("faceUrl");

        String faceContentBase64 = postParam.getString("faceContentBase64");

        String postSign = postParam.getString("sign");


        if (StringUtils.isEmpty(appId)
                || StringUtils.isEmpty(postSign)) {
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",appId);
        param.put("customerId",customerId.toString());


        String key = apiService.getKeyByAppID(appId);


        if (StringUtils.hasText(faceContentBase64)) {

            try {
                byte[] bytes1 = decoder.decodeBuffer(faceContentBase64);
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
                BufferedImage bi1 = ImageIO.read(bais);

                String uuid = UUID.randomUUID().toString();
//                File f1 = new File("/usr/local/nginx/html/openapi/" + uuid + ".png");
//                ImageIO.write(bi1, "png", f1);

                String filepath = "/usr/local/nginx/html/openapi/" + uuid + ".png";
                File f1 = new File(filepath);
                ImageIO.write(bi1, "png", f1);

                String fileUrl = filepath.replace(wxapiFilepath, "http://" + ipAddress);
//                String fileUrl = "https://binguoai.com/openapi/" + uuid + ".png";
                logger.info("上传成功:newFileName==" + fileUrl);
                faceUrl = fileUrl;
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else {
            if (StringUtils.hasText(faceUrl)) {
                String filepath = "/usr/local/nginx/html/openapi/source";
                File file = new File(filepath);

                if (!file.exists()) {
                    file.mkdir();
                }

                String uuid = UUID.randomUUID().toString();
                String filename = filepath + "/" + uuid + ".png";

                FileDownloader.downloadNet(faceUrl, filename);

                String fileUrl = filename.replace(wxapiFilepath, "http://" + ipAddress);
//                String fileUrl = "https://binguoai.com/openapi/source/" + uuid + ".png";

                param.put("faceUrl",faceUrl);
                faceUrl = fileUrl;
            }else {
                throw new ServiceException("参数错误");
            }
        }

        String sign = generateSign(param, key);

        logger.info(sign);

        if(!postSign.equals(sign)){
            throw new ServiceException("签名失败");
        }
        return ResultGenerator.genSuccessResult(apiService.addFace(customerId,faceUrl,appId));
    }

    @PostMapping(value = "/api/wxapp/openapi/getShopMsg", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取分店列表", notes = "")
    public Result getShopMsg(@RequestBody JSONObject postParam) {

        String phone = postParam.getString("phone");

        String channelNo = postParam.getString("channelNo");

        String postSign = postParam.getString("sign");


        if (StringUtils.isEmpty(channelNo)
                || StringUtils.isEmpty(postSign)
                || StringUtils.isEmpty(phone)) {
            throw new ServiceException("参数错误");
        }

        ShopChannel shopChannel = shopService.checkShopChannelNo(channelNo);

        String key = shopChannel.getChannelSecret();


        Map<String, String> param = new LinkedHashMap<>();
        param.put("channelNo",channelNo);
        param.put("phone",phone);


        String sign = generateSign(param, key);

        logger.info(sign);

        if(!postSign.equals(sign)){
            throw new ServiceException("签名失败");
        }
        return ResultGenerator.genSuccessResult(apiService.checkChannelShop(phone,shopChannel));
    }


    @PostMapping(value = "/api/wxapp/openapi/zhaoHangUpdate", produces = APPLICATION_JSON_VALUE)
    public Result zhaoHangUpdate(@RequestBody ApiRegisterForm registerForm) {
        if (StringUtils.isEmpty(registerForm.getPhone())
                || StringUtils.isEmpty(registerForm.getSign())
                || StringUtils.isEmpty(registerForm.getAppId())
                || StringUtils.isEmpty(registerForm.getUsername())
        ) {
            throw new ServiceException("参数错误");
        }

        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId",registerForm.getAppId());
        if(!StringUtils.isEmpty(registerForm.getCardNo())){
            param.put("cardNo",registerForm.getCardNo());
        }
        if (StringUtils.hasText(registerForm.getFaceUrl())) {
            param.put("faceUrl",registerForm.getFaceUrl());
        }
        param.put("phone",registerForm.getPhone());
        param.put("username",registerForm.getUsername());

        String key = apiService.getKeyByAppID(registerForm.getAppId());

        String sign = generateSign(param, key);

        logger.info(sign);

        if (!key.equals(registerForm.getSign())) {
            if (!registerForm.getSign().equals(sign)) {
                throw new ServiceException("签名失败");
            }
        }

        if (StringUtils.hasText(registerForm.getFaceContentBase64())) {

            try {
                byte[] bytes1 = decoder.decodeBuffer(registerForm.getFaceContentBase64());
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
                BufferedImage bi1 = ImageIO.read(bais);

                String uuid = UUID.randomUUID().toString();
//                File f1 = new File("/usr/local/nginx/html/openapi/" + uuid + ".png");
//                ImageIO.write(bi1, "png", f1);

                String filepath = "/usr/local/nginx/html/openapi/" + uuid + ".png";
                File f1 = new File(filepath);
                ImageIO.write(bi1, "png", f1);

                String fileUrl = filepath.replace(wxapiFilepath, "http://" + ipAddress);
//                String fileUrl = "https://binguoai.com/openapi/" + uuid + ".png";
                logger.info("上传成功:newFileName==" + fileUrl);
                registerForm.setFaceUrl(fileUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else if (StringUtils.hasText(registerForm.getFaceUrl())) {
            String filepath = "/usr/local/nginx/html/openapi/source";
            File file = new File(filepath);

            if (!file.exists()) {
                file.mkdir();
            }

            String uuid = UUID.randomUUID().toString();
            String filename = filepath + "/" + uuid + ".png";

            FileDownloader.downloadNet(registerForm.getFaceUrl(), filename);

            String fileUrl = filename.replace(wxapiFilepath, "http://" + ipAddress);
//          String fileUrl = "https://binguoai.com/openapi/source/" + uuid + ".png";

            registerForm.setFaceUrl(fileUrl);
        }

        //ApiCustomerBriefVO apiCustomerBriefVO = new ApiCustomerBriefVO();
        //apiCustomerBriefVO.setUserId(customerId);

        return ResultGenerator.genSuccessResult(apiService.zhaoHangUpDate(registerForm));
    }

    @PostMapping(value = "/api/wxapp/openapi/replaceFace", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取分店列表", notes = "")
    public Result replaceFace(@RequestBody JSONObject postParam) {

        String appId = postParam.getString("appId");

        Integer customerId = postParam.getInteger("customerId");

        String faceUrl = postParam.getString("faceUrl");

        String faceContentBase64 = postParam.getString("faceContentBase64");

        String postSign = postParam.getString("sign");


        if (StringUtils.isEmpty(appId)
                || StringUtils.isEmpty(postSign)) {
            throw new ServiceException("参数错误");
        }

        Map<String, String> param = new LinkedHashMap<>();
        param.put("appId",appId);
        param.put("customerId",customerId.toString());


        String key = apiService.getKeyByAppID(appId);


        if (StringUtils.hasText(faceContentBase64)) {

            try {
                byte[] bytes1 = decoder.decodeBuffer(faceContentBase64);
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
                BufferedImage bi1 = ImageIO.read(bais);

                String uuid = UUID.randomUUID().toString();
//                File f1 = new File("/usr/local/nginx/html/openapi/" + uuid + ".png");
//                ImageIO.write(bi1, "png", f1);

                String filepath = "/usr/local/nginx/html/openapi/" + uuid + ".png";
                File f1 = new File(filepath);
                ImageIO.write(bi1, "png", f1);

                String fileUrl = filepath.replace(wxapiFilepath, "http://" + ipAddress);
//                String fileUrl = "https://binguoai.com/openapi/" + uuid + ".png";
                logger.info("上传成功:newFileName==" + fileUrl);
                faceUrl = fileUrl;
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else {
            if (StringUtils.hasText(faceUrl)) {
                String filepath = "/usr/local/nginx/html/openapi/source";
                File file = new File(filepath);

                if (!file.exists()) {
                    file.mkdir();
                }

                String uuid = UUID.randomUUID().toString();
                String filename = filepath + "/" + uuid + ".png";

                FileDownloader.downloadNet(faceUrl, filename);

                String fileUrl = filename.replace(wxapiFilepath, "http://" + ipAddress);
//                String fileUrl = "https://binguoai.com/openapi/source/" + uuid + ".png";

                param.put("faceUrl",faceUrl);
                faceUrl = fileUrl;
            }else {
                throw new ServiceException("参数错误");
            }
        }

        String sign = generateSign(param, key);

        logger.info(sign);

        if(!postSign.equals(sign)){
            throw new ServiceException("签名失败");
        }
        return ResultGenerator.genSuccessResult(apiService.replaceFace(customerId,faceUrl,appId));

    }


    /**
     *  修改或新增配置接口
     * @return
     */
    @PostMapping(value = "/api/wxapp/openapi/updateOrAddConfig", produces = APPLICATION_JSON_VALUE)
    public Result updateProduct(@RequestBody ApiConfigForm form){
        logger.info("进入更新或修改配置接口,入参:"+form.toString());
        if (StringUtils.isEmpty(form.getAppId())
                || StringUtils.isEmpty(form.getUrl())
                || StringUtils.isEmpty(form.getSign())
        ) {
            throw new ServiceException("参数错误");
        }
        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId",form.getAppId());
        param.put("url",form.getUrl());
        String key = apiService.getKeyByAppID(form.getAppId());
        String sign = generateSign(param, key);
        logger.info("效验签名！  传入签名:"+form.getSign()+"生成签名:"+sign);
        if(!form.getSign().equals(sign)){
            throw new ServiceException("签名失败");
        }
        logger.info("执行normal_config表相关操作");
        int flag = apiService.updateOrAddConfig(form);
        return flag == 200 ? ResultGenerator.genSuccessResult() : ResultGenerator.genFailResult("操作失败！",flag);
    }
}
